package cn.w2.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

@ChannelHandler.Sharable
public class ModbusClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private static final Logger LOG = LoggerFactory.getLogger(ModbusClientHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        LOG.debug("通知-发送消息");
        byte[] bytes = {
                0x00, 0x03,
                0x00, 0x00,
                0x00, 0x06,
                0x02,
                0x03,
                0x00, 0x05,
                0x00, (byte) 0x02
        };
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(12);
        buf.writeBytes(bytes);
        /// 当被通知 Channel是活跃的时候，发送一条消息
        ctx.writeAndFlush(ctx.alloc().buffer().writeBytes(bytes));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        LOG.debug("channelRead0-{}",msg.toString(Charset.defaultCharset()));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log2((ByteBuf) msg);
//        super.channelRead(ctx, msg);
        ctx.close();
    }

    /**
     * 在处理过程中引发异常时被调用。
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }


    private static void log(ByteBuf buffer) {
        int length = buffer.readableBytes();
        int rows = length / 16 + (length % 15 == 0 ? 0 : 1) + 4;
        StringBuffer stringBuffer = new StringBuffer(rows * 80 * 2)
                .append("read index:").append(buffer.readerIndex())
                .append("write index:").append(buffer.writerIndex())
                .append("capacity:").append(buffer.capacity());

    }


    private static void log2(ByteBuf buffer) {
        String s = ByteBufUtil.hexDump(buffer);
        byte len = buffer.getByte(8);
        LOG.debug("接受到的Modbus 报文:{}", s);
        LOG.debug("接受到的Modbus 寄存器长度:{}", len);

        for (int i = 0; i < len; i += 2) {
            LOG.debug("值:{}", buffer.getShort(9 + i));
        }
    }
}
